import Vue from 'vue';
import axios from 'axios';
import Qs from 'qs';
import { LoadingPlugin } from 'vux'
Vue.use(LoadingPlugin)
let [isTest, href] = [null, window.document.location.href];
if (href.indexOf("192.168") > -1 || href.indexOf("localhost") > -1 || href.indexOf("36.7") > -1) {
  isTest = true
} else {
  isTest = false
}
const url = isTest ? 'http://192.168.3.71:8013' : 'http://hd4.wsloan.com/timestore'
//gyc http://192.168.22.45:8013  test:http://192.168.3.71:8013
window.url=url;
// 拦截器防止token失效
axios.interceptors.response.use(data => {
  if (data.data.code === 403) {
    localStorage.removeItem("timetoken");
    location.reload();
  } else {
    return data;
  }
})

let ajax = function (option) {
  let { url, method, headers = null, data, success,isFormData } = option;

  let config = {
    url,
    method,
  };
  if (headers) {
    Object.assign(config, { headers })
  }

  method.toLowerCase() === 'get' ? Object.assign(config, { params: data }) : Object.assign(config, { data });
  if (method.toLowerCase() === 'post' && !isFormData) {
    config.data = Qs.stringify(config.data);
  }
  console.log(data)
  let promise = axios(config);

  if (success && typeof success === 'function') {
    promise.then(res => success(res))
  }
  return promise;
};
window.initAjax = initAjax;

let initAjax = (method) => {
  return ({ api, data, isLoading = true,isFormData }, baseUrl) => {
    let innerUrl;
    let headers = localStorage.getItem("timetoken") ? { Authorization: localStorage.getItem("timetoken") } : null;
    if (baseUrl !== undefined) {
      innerUrl = baseUrl;
    } else {
      innerUrl = url;
    }
    if (isLoading) {
      Vue.$vux.loading.show({
        text: 'Loading'
      })
    }
    return ajax({
      url: innerUrl + api,
      method,
      headers,
      data,
      isFormData,
      success: () => {
        Vue.$vux.loading.hide()
      },
    })
  }
};

export default initAjax;
